import { getApiBaseUrlSync } from '../utils/apiConfig';

/**
 * 图片生成服务
 * 处理图片创建请求和任务状态轮询，支持页面状态检查避免错误渲染
 */
export class ImageService {
  private token: string | null = null;
  private translateFunction: ((key: string, params?: any) => string) | null = null;
  private uuid: string | null = null;
  private aiPersonId: string | number; // 新增：关联的AI角色ID
  private isCurrentPage: boolean = false; // 新增：标记是否是当前页面

  constructor(token?: string, aiPersonId?: string | number) {
    this.token = token || null;
    this.aiPersonId = aiPersonId || '';
    // 获取localStorage中的visitor_uuid
    try {
      const userDataStr = localStorage.getItem('userData');
      if (userDataStr) {
        const userData = JSON.parse(userDataStr);
        this.uuid = userData.visitor_uuid || null;
      }
    } catch (e) {
      this.uuid = null;
    }

    // 检查是否是当前页面的聊天
    this.updateCurrentPageStatus();
  }

  // 获取当前对话ID（优先从sessionStorage获取）
  private getCurrentConversationId(): string | number {
    // 优先从sessionStorage获取当前对话ID
    const sessionId = sessionStorage.getItem('currentConversationId');
    if (sessionId) {
      return sessionId;
    }
    
    // 如果sessionStorage中没有，使用构造函数传入的ID作为回退
    return this.aiPersonId || '';
  }

  // 检查并更新当前页面状态
  private updateCurrentPageStatus() {
    try {
      // 检查当前URL是否为聊天页面
      const currentUrl = window.location.pathname;
      const isConversationPage = currentUrl === '/conversation';
      
      // 如果是聊天页面，从sessionStorage获取当前聊天ID
      const currentChatId = isConversationPage ? sessionStorage.getItem('currentConversationId') : null;

      this.isCurrentPage = isConversationPage && currentChatId === String(this.getCurrentConversationId());
      // console.log(this.getText('imageService.logs.pageStatusCheck'), {
      //   currentUrl,
      //   currentChatId,
      //   serviceAiPersonId: this.aiPersonId,
      //   isCurrentPage: this.isCurrentPage
      // });
    } catch (e) {
      console.error(this.getText('imageService.logs.pageStatusCheckFailed'), e);
      this.isCurrentPage = false;
    }
  }

  // 设置AI角色ID
  setAiPersonId(aiPersonId: string | number) {
    this.aiPersonId = aiPersonId;
    this.updateCurrentPageStatus();
  }

  // 更新token
  setToken(token: string) {
    this.token = token;
  }

  // 设置翻译函数
  setTranslationFunction(translateFn: (key: string, params?: any) => string) {
    this.translateFunction = translateFn;
  }

  // 获取翻译文本的私有方法
  private getText(key: string, params?: any): string {
    if (this.translateFunction) {
      try {
        return this.translateFunction(key, params);
      } catch (error) {
        console.warn('Translation failed for key:', key, error);
      }
    }
    // 如果翻译失败，返回key作为默认值
    return key;
  }

  /**
   * 创建图片生成任务
   * @param prompt 用户提示词
   * @param aiPersonId AI角色ID
   * @param reserveId Token预留ID
   * @returns 返回任务ID和状态
   */
  async createImage(prompt: string, aiPersonId?: string | number, reserveId?: string): Promise<any> {
    try {
      // 获取当前对话ID（优先从sessionStorage）
      const currentConversationId = this.getCurrentConversationId();
      
      // 更新AI角色ID（如果传入了参数则使用传入的，否则使用当前对话ID）
      if (aiPersonId) {
        this.setAiPersonId(aiPersonId);
      }

      // 获取API基础URL
      const apiBaseUrl = getApiBaseUrlSync();
      // console.log(this.getText('imageService.logs.startImageGeneration'), {
      //   apiUrl: `${apiBaseUrl}/image/create`,
      //   prompt,
      //   aiPersonId: currentConversationId,
      //   isCurrentPage: this.isCurrentPage
      // });

      // 准备请求头
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
      };

      // 添加token到请求头
      if (this.token) {
        headers['Authorization'] = `Bearer ${this.token}`;
      }

      // 准备请求数据 - 使用当前对话ID
      const requestData: any = {
        character_trigger: "aikatsu!_(series),kiriya aoi,1girl,solo,(big breasts:1.2)", // 暂时使用固定值
        user_prompt: prompt,
        ai_person_id: currentConversationId,
        uuid: this.uuid // 添加uuid参数
      };

      // console.log(this.getText('imageService.logs.imageGenerationRequestData'), requestData);

      // 🪙 如果有预留ID，添加到请求中
      if (reserveId) {
        requestData.reserve_id = reserveId;
        // console.log(this.getText('imageService.logs.addReserveId'), reserveId);
      }

      // 发送请求
      const response = await fetch(`${apiBaseUrl}/image/create`, {
        method: 'POST',
        headers,
        body: JSON.stringify(requestData)
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      // console.log(this.getText('imageService.logs.imageTaskCreated'), data);
      return data;
    } catch (error) {
      console.error(this.getText('imageService.logs.createImageTaskFailed'), error);
      throw error;
    }
  }

  /**
   * 轮询获取任务状态（带页面状态检查）
   * @param taskId 任务ID
   * @param maxAttempts 最大尝试次数
   * @param interval 轮询间隔(ms)
   * @returns 返回任务完成状态和结果（如果页面已切换则返回null）
   */
  async pollTaskStatus(taskId: string, maxAttempts: number = 60, interval: number = 3000): Promise<any> {
    try {
      const apiBaseUrl = getApiBaseUrlSync();
      // console.log(`${this.getText('imageService.logs.startPollingTaskStatus')} ${taskId}`, {
      //   aiPersonId: this.aiPersonId,
      //   isCurrentPage: this.isCurrentPage
      // });

      // 准备请求头
      const headers: Record<string, string> = {};
      if (this.token) {
        headers['Authorization'] = `Bearer ${this.token}`;
      }

      // 轮询逻辑
      let attempts = 0;
      while (attempts < maxAttempts) {
        // 🔄 每次轮询前都检查页面状态
        this.updateCurrentPageStatus();

        // 如果不是当前页面，停止轮询并保存结果到正确的聊天历史
        if (!this.isCurrentPage) {
          // console.log(`${this.getText('chatService.logs.pageSwitchedStopPolling')} ${taskId}`, {
          //   aiPersonId: this.aiPersonId,
          //   currentUrl: window.location.pathname,
          //   attempts: attempts + 1
          // });

          // 继续轮询但不返回给调用方，而是保存到正确的聊天历史
          const backgroundResult = await this.continuePollingInBackground(taskId, maxAttempts - attempts, interval, headers, apiBaseUrl);
          if (backgroundResult) {
            await this.saveImageToCorrectChat(backgroundResult);
          }

          // 返回null表示页面已切换，不应该在当前页面显示结果
          return null;
        }

        // console.log(`${this.getText('imageService.logs.pollingTaskStatus')} (${attempts + 1}/${maxAttempts})...`);

        const response = await fetch(`${apiBaseUrl}/image/task/${taskId}`, {
          method: 'GET',
          headers
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        // console.log(`${this.getText('imageService.logs.taskStatus')} ${data.status}, progress: ${data.progress || 0}%`);

        // 如果任务完成，再次检查页面状态
        if (data.status === 'completed') {
          this.updateCurrentPageStatus();

          if (this.isCurrentPage) {
            // console.log(this.getText('imageService.logs.imageGenerationCompleted'), {
            //   imageUrl: data.image_url,
            //   processingTime: data.total_processing_time,
            //   isCurrentPage: this.isCurrentPage
            // });
            return data;
          } else {
            // console.log(this.getText('chatService.logs.imageCompletedButPageSwitched'));
            await this.saveImageToCorrectChat(data);
            return null;
          }
        }

        // 如果任务失败，抛出错误
        if (data.status === 'failed') {
          throw new Error(`${this.getText('imageService.errors.taskFailed')} ${data.error_message || this.getText('imageService.errors.unknownError')}`);
        }

        // 等待指定时间后再次轮询
        await new Promise(resolve => setTimeout(resolve, interval));
        attempts++;
      }

      // 超过最大尝试次数，抛出超时错误
      throw new Error(`${this.getText('imageService.errors.pollingTimeout')} (${maxAttempts * interval / 1000}${this.getText('imageService.errors.seconds')})`);
    } catch (error) {
      console.error(this.getText('imageService.logs.pollingTaskStatusFailed'), error);
      throw error;
    }
  }

  /**
   * 在后台继续轮询任务状态（用于页面切换后）
   */
  private async continuePollingInBackground(
    taskId: string,
    remainingAttempts: number,
    interval: number,
    headers: Record<string, string>,
    apiBaseUrl: string
  ): Promise<any> {
    try {
      // console.log(`${this.getText('chatService.logs.backgroundPollingStart')} ${taskId}，剩余尝试次数: ${remainingAttempts}`);

      let attempts = 0;
      while (attempts < remainingAttempts) {
        await new Promise(resolve => setTimeout(resolve, interval));

        const response = await fetch(`${apiBaseUrl}/image/task/${taskId}`, {
          method: 'GET',
          headers
        });

        if (!response.ok) {
          console.error(`${this.getText('chatService.logs.backgroundPollingError')}: ${response.status}`);
          return null;
        }

        const data = await response.json();
        // console.log(`${this.getText('chatService.logs.backgroundPollingStatus')} ${data.status}, progress: ${data.progress || 0}%`);

        // 如果任务完成，返回结果
        if (data.status === 'completed') {
          // console.log(`${this.getText('chatService.logs.backgroundPollingComplete')}:`, data.image_url);
          return data;
        }

        // 如果任务失败，返回null
        if (data.status === 'failed') {
          console.error(`${this.getText('chatService.logs.backgroundPollingFailed')}:`, data.error_message);
          return null;
        }

        attempts++;
      }

      console.warn(this.getText('chatService.logs.backgroundPollingTimeout'));
      return null;
    } catch (error) {
      console.error(`${this.getText('chatService.logs.backgroundPollingError')}:`, error);
      return null;
    }
  }

  /**
   * 将图片结果保存到正确的聊天历史中
   */
  private async saveImageToCorrectChat(taskResult: any): Promise<void> {
    try {
      // 获取当前对话ID
      const currentConversationId = this.getCurrentConversationId();
      
      if (!taskResult.image_url || !currentConversationId) {
        console.warn(this.getText('chatService.logs.invalidImageResult'));
        return;
      }

      // console.log(this.getText('chatService.logs.saveImageToChat'), {
      //   aiPersonId: currentConversationId,
      //   imageUrl: taskResult.image_url
      // });

      // 生成消息ID 
      const aiMessageId = `ai_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

      // 创建图片消息对象
      const imageMessage = {
        id: aiMessageId,
        type: 'image',
        content: this.getText('imageService.generatedImage'),
        sender: 'ai',
        timestamp: Date.now(),
        status: 'completed',
        imageUrl: taskResult.image_url,
        receivedAt: Date.now(),
        isImageGenerating: true
      };

      // 获取正确的聊天历史 - 使用当前对话ID
      const chatHistoryKey = `chat_history_${currentConversationId}`;
      let chatHistory: any = { messages: [] };

      try {
        const stored = localStorage.getItem(chatHistoryKey);
        if (stored) {
          chatHistory = JSON.parse(stored);
        }
      } catch (e) {
        console.error(this.getText('chatService.logs.getChatHistoryFailed'), e);
      }

      // 添加图片消息到聊天历史
      chatHistory.messages.push(imageMessage);

      // 保存更新后的聊天历史
      localStorage.setItem(chatHistoryKey, JSON.stringify(chatHistory));

      // console.log(this.getText('chatService.logs.imageSavedToChat'), {
      //   aiPersonId: currentConversationId,
      //   messageId: aiMessageId
      // });

      // 🔔 触发聊天历史更新事件，通知相关组件刷新 - 使用当前对话ID
      const event = new CustomEvent('chat-history-update', {
        detail: {
          chatId: currentConversationId,
          newMessage: imageMessage,
          timestamp: Date.now(),
          source: 'ImageService'
        }
      });
      window.dispatchEvent(event);

    } catch (error) {
      console.error(this.getText('chatService.logs.saveImageToChatFailed'), error);
    }
  }
}

/**
 * 使用示例：
 * 
 * 在React组件中：
 * ```typescript
 * import { ImageService } from '@/api/imageService';
 * import { useTranslation } from 'react-i18next';
 * 
 * const MyComponent = () => {
 *   const { t } = useTranslation();
 *   
 *   // 创建ImageService实例
 *   const imageService = new ImageService();
 *   
 *   // 设置翻译函数
 *   imageService.setTranslationFunction(t);
 *   
 *   // 现在可以使用国际化的ImageService
 *   const handleImageGeneration = async () => {
 *     try {
 *       const result = await imageService.createImage("prompt", "ai_person_id");
 *       // 处理结果...
 *     } catch (error) {
 *       // 错误消息已经国际化
 *       console.error(error.message);
 *     }
 *   };
 * };
 * ```
 * 
 * 在ChatService中：
 * ```typescript
 * import { ChatService } from '@/api/chatService';
 * import { useTranslation } from 'react-i18next';
 * 
 * const MyComponent = () => {
 *   const { t } = useTranslation();
 *   
 *   // 创建ChatService实例
 *   const chatService = new ChatService("chat_id");
 *   
 *   // 设置翻译函数
 *   chatService.setTranslationFunction(t);
 *   
 *   // 现在可以使用国际化的ChatService
 *   const handleSendMessage = async () => {
 *     try {
 *       await chatService.sendTextMessage("Hello", "en");
 *       // 处理结果...
 *     } catch (error) {
 *       // 错误消息已经国际化
 *       console.error(error.message);
 *     }
 *   };
 * };
 * ```
 */ 